package com.fuluwa.infra.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.PropertyFilter;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.alibaba.fastjson.serializer.ValueFilter;

public class JSONUtil {

	public static <T> T json2Object(String jsonString, Class<T> cls) {
		T t = null;
		try {
			t = (T) JSON.parseObject(jsonString, cls);
		} catch (Exception e) {
			Log.key.error("Convert json to object error!");
		}
		return t;
	}

	public static <T> List<T> json2List(String jsonString, Class<T> cls) {
		List<T> list = new ArrayList<T>();
		try {
			list = JSON.parseArray(jsonString, cls);
		} catch (Exception e) {
			Log.key.error("Convert json to list error!");
		}
		return list;
	}

	public static <T> String object2Json(T t, PropertyFilter propFilter, ValueFilter valueFilter) {
		SerializeWriter out = new SerializeWriter();
		JSONSerializer serializer = new JSONSerializer(out);
		serializer.getPropertyFilters().add(propFilter);
		serializer.getValueFilters().add(valueFilter);
		serializer.write(t);
		return serializer.toString();
	}

	public static <T> String list2Json(List<T> list, PropertyFilter propFilter, ValueFilter valueFilter) {
		SerializeWriter out = new SerializeWriter();
		JSONSerializer serializer = new JSONSerializer(out);
		serializer.getPropertyFilters().add(propFilter);
		serializer.getValueFilters().add(valueFilter);
		serializer.write(list);
		return serializer.toString();
	}

	public static String convertStream2Json(InputStream inputStream) {
		String jsonStr = "";
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		// 将输入流转移到内存输出流中
		try {
			while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {
				out.write(buffer, 0, len);
			}
			// 将内存流转换为字符串
			jsonStr = new String(out.toByteArray());
		} catch (IOException e) {
			Log.key.error("Convert string to json error!");
		}
		return jsonStr;
	}
}
